import { ref } from 'vue'

const useDraggable = () => {
  const transform = ref({
    offsetX: 0,
    offsetY: 0,
  })

  const handleHDialogMousedown = (e: MouseEvent) => {
    const mouseClientX = e.clientX
    const mouseClientY = e.clientY
    const { offsetX, offsetY } = transform.value

    const handleMousemove = (e: MouseEvent) => {
      const moveX = offsetX + e.clientX - mouseClientX
      const moveY = offsetY + e.clientY - mouseClientY

      transform.value.offsetX = moveX
      transform.value.offsetY = moveY
    }

    const handleMouseup = () => {
      document.removeEventListener('mousemove', handleMousemove)
      document.removeEventListener('mouseup', handleMouseup)
    }

    document.addEventListener('mousemove', handleMousemove)
    document.addEventListener('mouseup', handleMouseup)
  }

  const resetTransform = () => {
    Object.assign(transform.value, {
      offsetX: 0,
      offsetY: 0,
    })
  }

  return {
    transform,
    resetTransform,
    handleHDialogMousedown,
  }
}

export default useDraggable
